import tim from '../../tim'
import Cookies from 'js-cookie'
import wx from 'weixin-js-sdk'
const user = {
  state: {
    currentUserProfile: {},
    isLogin: false,
    isSDKReady: false, // TIM SDK 是否 ready
    userID: 0,
    userSig: '',
    sdkAppID: 0,
    healinfo: {}, // 登录用户个人信息
    exportType: 0,   // 判断对外输出类型：0：妙健康，1：cwi
    cwiappid: 1,    //appid
    nowtime: new Date().getTime(),
    userDinfo: {} //D端-群组内唯一用户信息
  },
  mutations: {
    upUserDinfo(state, info) {
      state.userDinfo = info||{}
    },
    upNowtime(state, time) {
      state.nowtime = time
    },
    upCwiappid(state, id) {
      state.cwiappid = id
    },
    upExportType(state, type) {
      state.exportType = type
    },
    updateHealinfo(state, healinfo) {
      state.healinfo = healinfo
    },
    updateCurrentUserProfile(state, userProfile) {
      state.currentUserProfile = userProfile
    },
    toggleIsLogin(state, isLogin) {
      state.isLogin = typeof isLogin === 'undefined' ? !state.isLogin : isLogin
    },
    toggleIsSDKReady(state, isSDKReady) {
      state.isSDKReady = typeof isSDKReady === 'undefined' ? !state.isSDKReady : isSDKReady
    },
    reset(state) {
      Object.assign(state, {
        currentUserProfile: {},
        isLogin: false,
        isSDKReady: false // TIM SDK 是否 ready
      })
    },
    GET_USER_INFO(state, payload) {
      state.userID = payload.userID
      state.userSig = payload.userSig
      state.sdkAppID = payload.sdkAppID
    },
  },
  actions: {
    login(context, userID) {
      tim
        .login({
          userID,
          userSig: window.genTestUserSig(userID).userSig
        })
        .then(() => {
          context.commit('toggleIsLogin', true)
          context.commit('startComputeCurrent')
          window.$message({ type: 'success', message: '登录成功' })
        })
        .catch(imError => {
          if (imError.code === 2000) {
            window.$message.error(imError.message + ', 请检查是否正确填写了 SDKAPPID')
          } else {
            window.$message.error(imError.message)
          }
        })
    },
    logout(context) {
      // 若有当前会话，在退出登录时已读上报
      if (context.rootState.conversation.currentConversation.conversationID) {
        tim.setMessageRead({ conversationID: context.rootState.conversation.currentConversation.conversationID })
      }
      tim.logout().then(() => {
        context.commit('toggleIsLogin')
        context.commit('stopComputeCurrent')
        context.commit('reset')
        Cookies.remove('token')
        Cookies.remove('profileId')
        Cookies.remove('userID')
        Cookies.remove('userSig')
        localStorage.removeItem('token')
        localStorage.removeItem('profileId')
        localStorage.removeItem('userID')
        localStorage.removeItem('userSig')
        wx.miniProgram.redirectTo({ url: '/pages/get-info/index'})
      })
    }
  }
}

export default user
